import path from 'path'
import { defineConfig, loadEnv } from 'vite'

import reactRefresh from '@vitejs/plugin-react-refresh'
import legacy from '@vitejs/plugin-legacy'
import styleImport from 'vite-plugin-style-import'

export default defineConfig(({ mode }) => {
  // 获取 dotEnv 环境变量
  const env = loadEnv(mode, process.cwd())
  const VITE_APP_PROXY_PREFIX = env['VITE_APP_PROXY_PREFIX']

  return {
    plugins: [
      reactRefresh(),
      legacy(),
      styleImport({
        libs: [
          {
            // antd(组件)样式按需加载
            libraryName: 'antd',
            esModule: true,
            resolveStyle: (name) => {
              return `antd/es/${name}/style/index`
            },
          },
        ],
      }),
    ],

    resolve: {
      // 配置路径别名
      alias: { '@': path.resolve(__dirname, './src') },
    },

    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true, // 允许 less 使用变量
          additionalData: `@import '@/styles/variables.less';`, // 全局注入变量
          modifyVars: { '@primary-color': '@theme-color' }, // 替换 antd 默认变量的值
        },
      },
    },

    server: {
      port: 8585,
      host: true,
      proxy: {
        [VITE_APP_PROXY_PREFIX]: {
          target: 'https://cnodejs.org/api/v1',
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`\^${VITE_APP_PROXY_PREFIX}`), ''),
        },
      },
    },

    build: {
      rollupOptions: {
        output: {
          // 把不同的依赖分组打包
          // 这里需要注意顺序,否则会报错
          manualChunks: {
            react: ['react', 'react-dom', 'react-router-dom'],
            mobx: ['mobx', 'mobx-react'],
            antd: ['antd'],
            axios: ['axios'],
          },
        },
      },
    },

    // 打包后资源引用的起始路径(解决同域名多个项目的问题)
    base: './',
  }
})
